import axios from 'axios'
import storage from './storage'
import router from '../router'
import Message from '@/components/message'

// http request 拦截器
axios.interceptors.request.use(
	config => {
		const token = storage.get('token')
		if(token){
			// Bearer是JWT的认证头部信息
			config.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
      config.headers.common['Authorization'] = 'Bearer ' + token
		}
		return config
	},
	err => {
		return Promise.reject(err)
	}
)

// http response 拦截器
axios.interceptors.response.use(
	res => {
		//获取更新的token
		const {authorization} = res.headers
		authorization && storage.set('token', authorization)
		//响应码错误提示
		if(res.data.errCode !== 0){
			Message.install({
				type: 'danger',
				content: res.data.errMsg
			})
			return Promise.reject(res.data)
		}
		return res.data.data
	},
	err => {
		if(err.response){
			switch(err.response.status){
				// 无权限
				case 401:
					router.push('/login')
					break
				case 404:
					break
				case 500:
					break
			}
		}
		return Promise.reject(err.response.data)
	}
)

export default axios